<template>
  <!-- 用户管理 -->
  <div style="position: relative;">
    <el-card style="height:calc( 100vh - 85px); overflow:auto; ">
      <!-- 信息搜索框 -->
      <userManageFrom :query-obj="queryObj" :role-list="roleList" @queryClickfn="queryClick" @resetQueryfn="resetQuery" />
      <!-- 调整状态按钮 -->
      <el-row style="margin-bottom:10px">
        <div style="float:left">
          <el-button v-permission="'UserManage-add'" type="primary" plain @click="addUserClick"><i class="el-icon-plus" /> 添加用户</el-button>
        </div>
        <div style="float:right">
          <div style="font-size:30px;display: inline-block;margin-right:5px">
            <a href="#">
              <el-tooltip class="item" effect="dark" content="列位置" placement="top" style="cursor:pointer">
                <el-dropdown trigger="click" :hide-on-click="false">
                  <span class="el-dropdown-link">
                    <i class="el-icon-s-grid el-icon--right" style="font-size:24px;color:black" />
                  </span>
                  <el-dropdown-menu slot="dropdown" style=" width:190px;height:300px;overflow:auto">
                    <el-dropdown-item><el-checkbox v-model="deleteCell.isuserNo">用户名</el-checkbox></el-dropdown-item>
                    <el-dropdown-item><el-checkbox v-model="deleteCell.isuserName">账号</el-checkbox></el-dropdown-item>
                    <el-dropdown-item><el-checkbox v-model="deleteCell.isroleId">角色</el-checkbox></el-dropdown-item>
                    <el-dropdown-item><el-checkbox v-model="deleteCell.isenabled">状态</el-checkbox></el-dropdown-item>
                    <el-dropdown-item><el-checkbox v-model="deleteCell.isoperate">操作</el-checkbox></el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-tooltip>
            </a>
          </div>
          <!-- 右侧公用按钮功能组件 -->
          <functionButton style="float:right" :refresh-click="refreshClick" :table-data="tableData" :table-data-all="tableDataAll" :headers-arr="headersArr" :headers-relations="headersRelations"
            @exportAllfn="exportAll" />
        </div>
      </el-row>

      <!-- 任务总表 -->
      <el-table v-loading="listLoading" :data="tableData" border :row-style="{height:'40px'}" :cell-style="{padding:'0px'}" style="width: 100%;  margin-bottom: 10px;overflow:auto;">
        <el-table-column v-if="deleteCell.isuserNo" prop="userNo" label="用户名" />
        <el-table-column v-if="deleteCell.isuserName" prop="userName" label="账号" />
        <el-table-column v-if="deleteCell.isroleId" prop="roleId" label="角色">
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            {{
              roleList.find(item => {
                return scope.row.roleId === item.id
              }).roleName
            }}
          </template>
        </el-table-column>
        <el-table-column v-if="deleteCell.isenabled" prop="enabled" label="状态">
          <template slot-scope="scope">
            <p>{{ scope.row.enabled?'启用':'禁用' }}</p>
          </template>
        </el-table-column>
        <el-table-column v-if="deleteCell.isoperate" label="操作">
          <template slot-scope="scope">
            <el-button v-permission="'UserManage-edit'" type="text" size="small" @click="editUserClick(scope.row)">编辑</el-button>
            <el-button v-permission="'UserManage-delete'" type="text" size="small" @click="deleteUserClick(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <paging :pagion-obj="pagionObj" :handle-size-change="handleSizeChange" :handle-page-change="handlePageChange" />
    </el-card>
    <!-- 添加用户或者编辑用户的dialog -->
    <el-dialog :title="dialogName" top="5vh" width="40%" :before-close="handleClose" :visible.sync="UserManageVisible">
      <el-form ref="userAddData" :model="userAddData" :rules="rules" size="small" label-width="100px">
        <el-form-item label="账号" prop="userName">
          <el-input v-model.trim="userAddData.userName" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="用户名" prop="userNo">
          <el-input v-model.trim="userAddData.userNo" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item v-if="adddialogbutton" label="密码" prop="password">
          <el-input v-model.trim="userAddData.password" show-password placeholder="请输入密码" />
        </el-form-item>
        <el-form-item v-if="adddialogbutton" label="确认密码" prop="checkPassword">
          <el-input v-model.trim="userAddData.checkPassword" show-password placeholder="确认密码" />
        </el-form-item>
        <el-form-item v-if="editdialogbutton && changePassword" label="密码" prop="password">
          <el-input v-if="changePassword" v-model.trim="userAddData.password" show-password placeholder="密码" />
        </el-form-item>
        <el-form-item v-if="editdialogbutton && changePassword" label="确认密码" prop="checkPassword">
          <el-input v-if="changePassword" v-model.trim="userAddData.checkPassword" show-password placeholder="确认密码" />
        </el-form-item>
        <el-form-item v-if="editdialogbutton &&!changePassword">
          <el-button v-if="!changePassword" @click="changePassword = true">修改密码</el-button>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="userAddData.roleId" placeholder="请选择角色">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-if="adddialogbutton" type="primary" plain size="medium" @click="addUserConfirm">确认</el-button>
          <el-button v-if="editdialogbutton" type="primary" plain size="medium" @click="editUserConfirm">修改</el-button>
          <el-button size="medium" @click="handleClose">取消</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>
  </div>

</template>

<script>
import {
  queryUserApi,
  addUserApi,
  queryRoleApi,
  deleteUserApi,
  editUserApi,
} from "@/api/manage";
import { Message } from "element-ui";
import permission from "@/permission/index.js"; // 权限判断指令
import userManageFrom from "./components/userManageFrom.vue";
export default {
  name: "UserManage",
  directives: { permission },
  components: {
    userManageFrom,
  },
  data() {
    // 密码的自定义校验
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (value.length < 6) {
          callback(new Error("密码不能小于6位"));
        } else {
          callback();
        }
      }
    };
    // 确认密码的自定义校验
    var validatCheckePass = (rule, value, callback) => {
      if (value !== this.userAddData.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      queryObj: {
        userNo: "", // 用户名
        userName: "", // 账号
        roleId: 0, // 角色
        page: 0, // 第几页
        size: 0, // 每页条数
      },
      // 分页的数据
      pagionObj: {
        size: 10,
        currentPage: 1,
        total: 100,
      },
      // 请求返回的数据
      tableData: [],
      tableDataAll: [],
      isopen: false,
      // 页面loding效果
      listLoading: true,
      // dialog名
      dialogName: "添加用户",
      // 添加dialog按钮
      adddialogbutton: false,
      // 编辑dialog按钮
      editdialogbutton: false,
      // UserManage的dialog显示
      UserManageVisible: false,
      // 角色列表数据
      roleList: [],
      // 修改密码框是否显示
      changePassword: false,
      // 添加/编辑用户的数据
      userAddData: {
        userNo: "",
        userName: "",
        password: "",
        // 确认密码
        checkPassword: "",
        roleId: "",
      },
      // 表单校验
      rules: {
        userNo: [
          { required: true, message: "必填哦！", trigger: ["blue", "change"] },
        ],
        userName: [
          { required: true, message: "必填哦！", trigger: ["blue", "change"] },
        ],
        password: [
          { required: true, message: "必填哦！", trigger: ["blue", "change"] },
          { validator: validatePass, trigger: ["blue", "change"] },
        ],
        checkPassword: [
          { required: true, message: "必填哦！", trigger: ["blue", "change"] },
          { validator: validatCheckePass, trigger: ["blue", "change"] },
        ],
        roleId: [
          { required: true, message: "请选择好角色", trigger: ["blue"] },
        ],
      },
      // 列位置数据
      deleteCell: {
        isuserNo: true,
        isuserName: true,
        isroleId: true,
        isenabled: true,
        isoperate: true,
      },
      // excel 数据的key 表头数据
      headersArr: ["用户名", "账号", "角色", "状态"],
      // 将表头转换成中文
      headersRelations: {
        用户名: "userNo",
        账号: "userName",
        角色: "roleId",
        状态: "enabled",
      },
    };
  },
  // 监视时间变化
  watch: {
    timestart_end(newData) {
      if (newData !== null && newData.length > 0) {
        this.queryObj.startTime = this.timestart_end[0];
        this.queryObj.endTime = this.timestart_end[1];
      } else {
        this.queryObj.startTime = "0001/1/1 0:00:00";
        this.queryObj.endTime = "0001/1/1 0:00:00";
      }
    },
  },
  created() {
    this.getRoleData();
  },
  mounted() {
    this.queryData();
  },
  methods: {
    /** 获取页面数据*/
    async queryData() {
      this.listLoading = true;
      this.queryObj.size = this.pagionObj.size;
      this.queryObj.page = this.pagionObj.currentPage;
      const res = await queryUserApi(this.queryObj);
      this.tableData = res.data.data;
      this.pagionObj.pageCount = res.data.pageCount;
      this.pagionObj.total = res.data.count;
      this.listLoading = false;
    },
    // 获取角色
    async getRoleData() {
      const res = await queryRoleApi(this.queryObj);
      this.roleList = res.data.data;
    },
    // 搜索按钮
    queryClick() {
      this.pagionObj.currentPage = 1;
      this.queryData();
    },
    // 刷新按钮
    refreshClick() {
      this.listLoading = true;
      this.queryData();
      this.listLoading = false;
    },
    /** 每页显示数据变化*/
    handleSizeChange(val) {
      this.pagionObj.size = val;
      this.queryData();
    },
    /** 当前页变化*/
    handlePageChange(val) {
      this.pagionObj.currentPage = val;
      this.queryData();
    },
    // 重置按钮
    resetQuery() {
      this.queryObj.userNo = "";
      this.queryObj.userName = "";
      this.queryObj.roleId = 0;
    },
    // 添加用户
    addUserClick() {
      this.dialogName = "添加用户";
      this.editdialogbutton = false;
      this.UserManageVisible = true;
      this.adddialogbutton = true;
    },
    // 添加用户确认按钮
    addUserConfirm() {
      this.$refs.userAddData.validate(async (valid) => {
        if (valid) {
          await addUserApi(this.userAddData);
          this.queryData();
          this.UserManageVisible = false;
          this.$refs.userAddData.resetFields();
        } else {
          Message.error("数据输入有误");
          return false;
        }
      });
    },
    // 编辑用户
    editUserClick(data) {
      this.dialogName = "编辑用户";
      this.adddialogbutton = false;
      this.UserManageVisible = true;
      this.editdialogbutton = true;
      this.userAddData.id = data.id;
      this.userAddData.userNo = data.userNo;
      this.userAddData.userName = data.userName;
      this.userAddData.roleId = data.roleId;
      if (this.changePassword) {
        this.userAddData.password = data.password;
      }
    },
    // 编辑确认更新用户
    editUserConfirm() {
      this.$refs.userAddData.validate(async (valid) => {
        if (valid) {
          if (this.userAddData.password === this.userAddData.checkPassword) {
            await editUserApi(this.userAddData);
            Message.success("修改成功");
            this.queryData();
            this.UserManageVisible = false;
          } else {
            Message.error("两次输入密码不一致");
          }
        } else {
          Message.error("数据输入有误");
          return false;
        }
      });
    },
    // 删除用户
    async deleteUserClick(data) {
      const id = data.id;
      this.$confirm("确认删除当前用户吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await deleteUserApi([{ id }]);
          this.queryData();
        })
        .catch(() => {});
    },
    // 关闭dialog
    handleClose() {
      // 添加dialog按钮
      this.adddialogbutton = false;
      // 编辑dialog按钮
      this.editdialogbutton = false;
      // UserManage的dialog显示
      this.UserManageVisible = false;
      // 修改密码框是否显示
      this.changePassword = false;
      this.userAddData = {
        userNo: "",
        userName: "",
        password: "",
        roleId: "",
        checkPassword: "",
      };
    },
    // excel导出全部
    async exportAll() {
      const res2 = await queryUserApi({ size: 10000 });
      this.tableDataAll = res2.data.data;
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
